import 'package:get/get.dart';
import '../../../app/services/storage/secure_storage_service.dart';
import '../../../app/services/auth_service.dart';

/// 认证修改器 - 负责给请求添加认证头
/// 从安全存储中获取token并添加到请求头
Future<Request> authModifier(Request request) async {
  try {
    final secureStorage = Get.find<SecureStorageService>();
    final authService = Get.find<AuthService>();
    
    // 检查是否需要认证
    if (authService.isLoggedIn) {
      final token = await secureStorage.read('access_token');
      
      if (token != null && token.isNotEmpty) {
        // 如果token即将过期，尝试刷新
        if (authService.shouldRefreshToken) {
          await authService.refreshToken();
          final newToken = await secureStorage.read('access_token');
          request.headers['Authorization'] = 'Bearer $newToken';
        } else {
          request.headers['Authorization'] = 'Bearer $token';
        }
      }
    }
    
    return request;
  } catch (e) {
    // 如果获取token失败，继续请求但不添加token
    return request;
  }
} 